/**
 * Created by houjianhui on 2017/7/19.
 */

'use strict';
angular.module('kasApp', ['ui.router', 'wms.controllers', 'wms.services','wms.filter','ngDialog','restangular','ui.select','wms.constant'])
    .constant('Settings', {
        Context: {
            path: contextPath
        }
    })
    .run(['$rootScope', '$location', '$state', 'Settings','Tools','constant','dropDownService', function ($rootScope, $location, $state, Settings,Tools,constant,dropDownService) {
        $rootScope.$ = layui.jquery;
        layui.use(['element', 'form', 'laydate'], function () {
            $rootScope.elements = layui.element();
            $rootScope.$ = layui.jquery;
            $rootScope.form = layui.form();
            $rootScope.laydate = layui.laydate;

        });
        $rootScope.active = {
            tabAdd: function(id, titleName, content, url){
                if (tabIsExit(titleName) > -1) {//判断是否有tab页，>-1存在
                    var tabId = getTabId(titleName);
                    $rootScope.elements.tabChange('tab_kas', tabId);
                    $rootScope.$('#index_content').addClass('layui-show');
                    $state.go(url);
                } else {
                    addTab(id, titleName, content, url);
                }
            }
        };

        //刷新事件(刷新，默认显示首页)
       /* $rootScope.$on('$locationChangeStart', function (event) {
            var  go_href =$(".layui-tab").find("li.layui-this span").attr("data-url");
            if(!go_href){
                $state.go('index');
            }else{
                event.preventDefault();
            }
        });*/

        function addTab(id, titleName, content, url) {//添加tab页
            var title = '';
            title += '<span id = "' + id + '" data-url ="'+ url +'">' + titleName + '</span>';
            title += '<i class="layui-icon layui-unselect layui-tab-close" data-id ="'+ id +'">&#x1006;</i>';
            var div = 'div_' + id;
            //添加tab
            $rootScope.elements.tabAdd('tab_kas', {
                title: title,
                id: id
            });

            $rootScope.$('.layui-tab-content').children('div.layui-tab-item').eq(1).remove();
            $rootScope.$('#index_content').addClass('layui-show');

            $rootScope.elements.tabChange('tab_kas', id);

            $rootScope.$('.layui-tab').find('li').children('i.layui-tab-close[data-id='+ id +']').on('click', function () {
                $rootScope.elements.tabDelete("tab_kas", $(this).parent('li').attr('lay-id')).init();//关闭tab_title
                //点击x，关闭tab页
                var  go_href =$(".layui-tab").find("li.layui-this span").attr("data-url");
                if(!go_href){
                    $state.go('index');
                }else{
                    $state.go(go_href);
                }
            });
            //点击tab，进行切换
            $rootScope.$('.layui-tab').find('li[lay-id='+id+']').bind('click', function () {
                var tab_url = $(this).find('span').attr('data-url');
                $state.go(tab_url);//切换tab页
            });
            $state.go(url);//切换首页
        }

        function getTabId(title) {//获取tab页的id
            var tabId = -1;
            $rootScope.$('.layui-tab').find('li').each(function (i, e) {
                var $cite = $(this).children('span');
                if ($cite.text() === title) {
                    tabId = $(this).attr('lay-id');
                };
            });
            return tabId;
        }

        function tabIsExit(title) {//获取tab页是否存在，存在1，不存在-1
            var tabIndex = -1;
            $rootScope.$('.layui-tab').find('li').each(function (i, e) {
                var $cite = $(this).children('span');
                if ($cite.text() === title) {
                    tabIndex = i;
                };
            });
            return tabIndex;
        }

        // 初始化banner
        function initNav() {
            $.ajax({
                url: contextPath + '/public/js/data/nav_data.json',
                type: 'GET',
                async: false,
                dataType: 'json',
                success: function (result, status, xhr) {
                    $rootScope.navList = result;
                    if (result != null) {
                        angular.forEach(result, function (item) {
                            if (item.default) {
                                initMenu(item.id);
                            }
                        })
                    }
                }
            });
        }

        function initMenu(id) {
            $.ajax({
                url: contextPath + '/public/js/data/menu_data.json',
                type: 'GET',
                async: false,
                dataType: 'json',
                success: function (result, status, xhr) {
                    if (result != null) {
                        angular.forEach(result, function (item) {
                            if (item.id == id) {
                                $rootScope.menuList = item.list;
                            }
                        })
                    }
                }
            });
        }

        $rootScope.totalPage = 0;
        $rootScope.pageNo = 1;
        $rootScope.rootNewClip = function(obj,fun){
            layui.use(['laypage'],function(){
                var laypage = layui.laypage;
                laypage({
                    cont: $(obj)
                    , pages: $rootScope.totalPage
                    , last: "" + $rootScope.totalPage+" 页，共"+ $rootScope.totalRecord +" 条记录"
                    , skip: true
                    ,curr : $rootScope.curr,
                    jump: function (obj, first) {
                        if (!first) {
                            //保存当前的页码，以备刷新当前页
                            $rootScope.curr = obj.curr;
                            fun(obj.curr);
                        }
                    }
                });
            })
        };

        // 注销
        $rootScope.logOut = function () {
            location.href = Settings.Context.path
        };
        //设置工具类 可以直接访问
        $rootScope.Tools = Tools;
        //设置常量类 可以直接访问
        $rootScope.constant = constant;
        // 下拉service
        $rootScope.dropDownService = dropDownService;

        initNav();
    }])
    .config(['$stateProvider', '$urlRouterProvider', '$httpProvider', '$locationProvider','RestangularProvider','Settings', function ($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider,RestangularProvider,Settings) {

        $stateProvider
            .state('index', {   //主页
                url: '/index',
                templateUrl: contextPath + '/public/template/index.html'
            }).state('in-storage-bill', {   //入库单管理
                controller : 'inStorageBillCtrl',
                url: '/in-storage-bill',
                templateUrl: contextPath + '/public/template/inStorageManagement/inStorageBill/in-storage-bill-list.html'
            }).state('input-work', {    //入库作业管理
                controller : 'inputWorkCtrl',
                url: '/input-work',
                templateUrl: contextPath + '/public/template/inStorageManagement/inputWork/input-work-list.html',
            }).state('warehouse', {  //出库管理
                url: '/warehouse',
                templateUrl: contextPath + '/public/template/warehouseManagement/warehouse/warehouse-list.html',
                controller:'warehouseCtrl'
            }).state('outbound-order', {  //备料单查询
                url: '/outbound-order',
                templateUrl: contextPath + '/public/template/warehouseManagement/outboundOrder/outbound-order-list.html',
                controller : 'outboundOrderCtrl'
            }).state('inventory-select', {  //库存查询
                url: '/inventory-select',
                templateUrl: contextPath + '/public/template/inventoryManagement/inventorySelect/inventory-select-list.html',
                controller : 'inventorySelectCtrl'
             }).state('inventory-overview', {    //库存概况
                url: '/inventory-overview',
                templateUrl: contextPath + '/public/template/inventoryManagement/inventoryOverview/inventory-overview-list.html'
            }).state('repair-bill', {    //维修单管理
                controller : 'repairBillCtrl',
                url: '/repair-bill',
                templateUrl: contextPath + '/public/template/maintenanceManagement/repairBill/repair-bill-list.html'
            }).state('reservoir', { //库区管理
                controller : 'reservoirCtrl',
                url: '/reservoir',
                templateUrl: contextPath + '/public/template/locationManagement/reservoirManagement/reservoir-list.html'
            }).state('stock-unit', {    //库位管理
                controller : 'stockUnitCtrl',
                url: '/stock-unit',
                templateUrl: contextPath + '/public/template/locationManagement/stockUnitManagement/stock-unit-list.html'
            })
            .state('stock-unit-strategy', {    //库位策略管理
                controller : 'stockUnitStrategyCtrl',
                url: '/stock-unit-strategy',
                templateUrl: contextPath + '/public/template/strategyManagement/stockUnitStrategy/stock-unit-strategy-list.html'
            })

        $urlRouterProvider.otherwise('index');

        //配置restangular路径
        RestangularProvider.setBaseUrl(Settings.Context.path);

        // 使angular $http post提交和jQuery一致
       /* $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';*/

        // Override $http service's default transformRequest
       /* $httpProvider.defaults.transformRequest = [function (data) {
            /!**
             * The workhorse; converts an object to x-www-form-urlencoded serialization.
             * @param {Object} obj
             * @return {String}
             *!/
            var param = function (obj) {
                var query = '';
                var name, value, fullSubName, subName, subValue, innerObj, i;

                for (name in obj) {
                    value = obj[name];

                    if (value instanceof Array) {
                        for (i = 0; i < value.length; ++i) {
                            subValue = value[i];
                            fullSubName = name + '[' + i + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    } else if (value instanceof Object) {
                        for (subName in value) {
                            subValue = value[subName];
                            fullSubName = name + '[' + subName + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    } else if (value !== undefined && value !== null) {
                        query += encodeURIComponent(name) + '='
                            + encodeURIComponent(value) + '&';
                    }
                }

                return query.length ? query.substr(0, query.length - 1) : query;
            };

            return angular.isObject(data) && String(data) !== '[object File]'
                ? param(data)
                : data;
        }];*/
    }])